package cn.itcast.nems.common.service.impl;

import cn.itcast.nems.common.service.AfterTransactionCommitExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * author liyong
 * create: 2024-04-09 09:11:43
 **/
@Component
public class AfterTransactionCommitExecutorImpl implements AfterTransactionCommitExecutor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void addRunnable(Runnable runnable) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            logger.info("添加事务提交后执行逻辑");
            TransactionSynchronizationManager.registerSynchronization(new RunnableTransactionSynchronization(runnable));
        } else {
            logger.info("当前没有事务上下文，直接执行逻辑");
            runnable.run();
        }
    }
}

class RunnableTransactionSynchronization implements TransactionSynchronization {
    private final Runnable runnable;

    public RunnableTransactionSynchronization(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void afterCommit() {
        runnable.run();
    }
}